package BaseServer

import (
	"SGNet"
	log "misc/seelog"
	"time"
)

const (
	Server_Gate  = -1
	Server_Hall  = 0
	Server_Scene = 1
)

type IServer interface {
	PushMessage(*SGNet.Message)
	GetServerType() int
}

const (
	MessageType_Client  = 0
	MessageType_Command = 1
)

type BaseServer struct {
	InMessageQueue  chan *SGNet.Message
	messageHandlers map[uint16]SGNet.ServerHandlerFunc
	commandandlers  map[uint16]SGNet.ServerHandlerFunc
}

func (baseServer *BaseServer) New() {
	baseServer.messageHandlers = make(map[uint16]SGNet.ServerHandlerFunc)
	baseServer.commandandlers = make(map[uint16]SGNet.ServerHandlerFunc)
	baseServer.InMessageQueue = make(chan *SGNet.Message, 10)
}

func (baseServer *BaseServer) Run() {
	go baseServer.Loop()
}
func (baseServer *BaseServer) Loop() {
	ticker := time.Tick(time.Millisecond)
	for _ = range ticker {
		baseServer.ProcessMessages()
	}
}

func (baseServer *BaseServer) PushMessage(message *SGNet.Message) {
	baseServer.InMessageQueue <- message
}

func (baseServer *BaseServer) ProcessMessages() {
	count := len(baseServer.InMessageQueue)
	for i := 0; i < count; i++ {
		msg := <-baseServer.InMessageQueue
		switch msg.Type {
		case MessageType_Client:
			if fn, ok := baseServer.messageHandlers[msg.Id]; ok {
				fn(msg)
			} else {
				log.Info("收到了不存在的消息包", msg.Id)
			}
		case MessageType_Command:
			if fn, ok := baseServer.commandandlers[msg.Id]; ok {
				fn(msg)
			} else {
				log.Info("收到了不存在的消息包", msg.Id)
			}
		}
	}
}

func (baseServer *BaseServer) AddNetHandler(id uint16, fn SGNet.ServerHandlerFunc) {
	baseServer.messageHandlers[id] = fn
}

func (baseServer *BaseServer) AddCommandHandler(id uint16, fn SGNet.ServerHandlerFunc) {
	baseServer.commandandlers[id] = fn
}
